import React, {useEffect, useRef, useState} from 'react';
import type {ActionType, ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {ProForm, ProTable} from '@ant-design/pro-components';
import {Modal, Button, Form, Select, message} from 'antd';
import {listDatasourceByProjectIdUsingPost, listDataSourceUsingGet} from "@/services/easyapi/eDatasource";
import {
  addProjectDatasourceUsingPost,
  removeProjectDatasourceUsingPost
} from "@/services/easyapi/eProject";

export enum UserOperationActions {
  BIND_USER = "bindUser",
  LIFT_USER = "liftUser",
  EMPOWER_USER = "empowerUser",
  REVOKE_USER = "revokeUser",
}

export type Props = {
  project: API.ProjectVo;
  visible: boolean;
  onCancel: () => void;
};

const initialData: API.ProjectVo[] = [];

const DatasourceProjectOperation: React.FC<Props> = (props) => {
  const {visible, onCancel, project} = props;
  const formRef = useRef<ProFormInstance<any>>();
  const [dataSource, setDataSource] = useState<API.RoleVo[]>(initialData);
  const [isAddModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [options, setOptions] = useState<API.RoleVo[]>([]);
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    if (visible) {
      // Fetch user roles when the modal becomes visible
      fetchDatasourceByProjectId();
    }
  }, [visible]);
  const fetchDatasourceByProjectId = async () => {
    const res = await listDatasourceByProjectIdUsingPost({
      projectId: project.id
    })
    if (res.code === 200) {
      setDataSource(res.data || []);
    }
  }
  const columns: ProColumns<API.DataSourceListVo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '数据源名称',
      dataIndex: 'dataName',
      width: '30%',
    },
    {
      title: '数据源描述',
      dataIndex: 'dataDesc',
      width: '50%',
    },
    {
      title: '操作',
      valueType: 'option',
      width: '20%',
      render: (_, record) => {
        return (
          <Button
            type="link"
            danger
            // @ts-ignore
            onClick={() => handleRevoke(project.id, record.id)}
          >
            取消引用
          </Button>
        );
      },
    },
  ];

  const listDatasource = async () => {
    const res = await listDataSourceUsingGet();
    setOptions(
      //@ts-ignore
      res.data.map((datasource) => ({
        label: datasource.dataName,
        value: datasource.id,
      })) || []
    );
  };
  const handleAdd = async () => {
    const datasourceId = await form.validateFields();
    const res = await addProjectDatasourceUsingPost({
      datasourceId: datasourceId.id,
      projectId: project.id
    })
    if (res.code === 200) {
      message.success('添加成功');
      setAddModalVisible(false);
      fetchDatasourceByProjectId();
    } else {
      message.error(res.msg);
    }

  };

  const handleRevoke = async (projectId:number, datasourceId:number) => {
    removeProjectDatasourceUsingPost({
      projectId: projectId,
      datasourceId: datasourceId
    }).then(res=>{
      if (res.code === 200) {
        message.success('取消引用成功');
        fetchDatasourceByProjectId();
      } else {
        message.error(res.msg);
      }
    })
  };

  return (
    <>
      <Modal width="40%" visible={visible} footer={null} onCancel={onCancel}>
        <ProForm<{
          table: API.ProjectVo[];
        }>
          formRef={formRef}
          initialValues={{
            table: dataSource,
          }}
          validateTrigger="onBlur"
          submitter={false} // Disable the submit button and other controls
        >
          <ProTable<API.ProjectVo>
            rowKey="id"
            scroll={{
              x: 500,
            }}
            actionRef={actionRef}
            //@ts-ignore
            request={fetchDatasourceByProjectId}
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            search={false}
            toolBarRender={() => [
              <Button
                type="primary"
                onClick={() => {
                  listDatasource()
                  setAddModalVisible(true)
                }} // Updated to call handleAdd
              >
                引用数据源
              </Button>,
            ]}
          />
        </ProForm>
      </Modal>

      <Modal
        title="新增数据源引用..."
        visible={isAddModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAdd}
        >
          <Form.Item
            name="id"
            label="数据源"
            rules={[{required: true, message: '角色为必填项'}]}
          >
            <Select
              options={options}
              placeholder="请选择角色"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default DatasourceProjectOperation;
